package pers.hl.module_login

import android.os.Bundle
import android.view.View
import androidx.lifecycle.Observer
import com.alibaba.android.arouter.facade.annotation.Route
import com.blankj.utilcode.util.NotificationUtils
import pers.hl.common.base.BaseVBVMActivity
import pers.hl.common.utils.SoftInputHelper
import pers.hl.lib_global.arouter.RouterPath
import pers.hl.lib_global.common.Const
import pers.hl.lib_global.common.MMKVHelper
import pers.hl.lib_global.common.RouteUtils
import pers.hl.lib_global.model.bean.User
import pers.hl.module_login.databinding.LoginActivityLoginBinding

@Route(path = RouterPath.login)
class LoginActivity : BaseVBVMActivity<LoginActivityLoginBinding, LoginViewModel>() {

    override fun initView(savedInstanceState: Bundle?) {
        clearNotification()
//        val softInputHelper = SoftInputHelper.attach(this).moveBy(mBinding.root)
        mBinding.apply {
            progressBar.isIndeterminate = false
//            softInputHelper.moveWith(btRegister, etAccount.editText, etPassword.editText)
            btLogin.setOnClickListener {
                val account = etAccount.text
                val password = etPassword.text
                showLoading()
                mViewModel.login(account, password)
            }
            btRegister.setOnClickListener {
                val account = etAccount.text.toString()
                val password = etPassword.text.toString()
                mViewModel.register(account, password).observe(this@LoginActivity, Observer {
                    mViewModel.login(account, password)
                })
            }
            if (MMKVHelper.savePassword) {
                val user = MMKVHelper.getUser()
                etAccount.editText.setText(user?.account)
                etPassword.editText.setText(user?.password)
            }
            mViewModel.loginUserData.observe(this@LoginActivity, Observer {
                mBinding.apply {
                    hideLoading()
                    if (it.isAdmin()) {
                        RouteUtils.nav(RouterPath.mainAdmin)
                    } else {
                        RouteUtils.nav(RouterPath.main)
                    }
                    finish()
                }
            })
        }
    }

    private fun clearNotification() {
        NotificationUtils.cancelAll()
    }

    override fun initData(savedInstanceState: Bundle?) {
        val intent = intent
        if (intent != null) {
            val msg = intent.getStringExtra(Const.KEY.NEED_LOGIN)
            val user = intent.getParcelableExtra<User>(Const.KEY.KEY_USER)
            mBinding.apply {
                user?.apply {
                    etAccount.editText.setText(user.userName)
                }
            }
        }

    }

    override fun showLoading() {
        mBinding.progressBar.visibility = View.VISIBLE
    }

    override fun hideLoading() {
        mBinding.progressBar.visibility = View.INVISIBLE
    }


}
